package com.threeti.mecool.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.threeti.mecool.core.application.acl.UserService;
import com.threeti.mecool.core.domain.model.acl.Role;
import com.threeti.mecool.core.infrastructure.persistence.UserRepository;
import com.threeti.mecool.web.form.UserForm;

@Controller
public class AuthController {
  @Autowired
  UserRepository userRepository;

  @Autowired
  UserService userService;

  @RequestMapping(value = "/login.html", method = RequestMethod.GET)
  public String login(@RequestParam(value = "login_error", required = false) boolean error, Model model) {
    if (error) {
      model.addAttribute("error", "用户名或密码不正确");
    }
    return "/auth/login";
  }

  @RequestMapping(value = "/denied.html", method = RequestMethod.GET)
  public String denied() {
    return "/auth/denied";
  }

  @RequestMapping(value = "/register.html", method = RequestMethod.GET)
  public String registerPage(UserForm userForm) {
    List<Role> roles = userService.getUserFromSession().getRoles();
    userForm.setRoles(roles);

    return "/admin/newUserForm";
  }

  @RequestMapping(value = "/doregister.html", method = RequestMethod.POST)
  public String register(UserForm userForm) {

    try {
      userService.register(userForm.getLoginName(), userForm.getDisplayName(), userForm.getPassword());
      return "/admin/userMain";
      
    } catch (Exception e) {
      e.printStackTrace();
      //TODO jay 异常处理
      return "/admin/newUserForm";
    }
  }
}
